package org.example.trigger.listener;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.example.domain.award.event.SendAwardMessageEvent;
import org.example.domain.award.model.entity.DistributeAwardEntity;
import org.example.domain.award.service.IAwardService;
import org.example.domain.award.service.distribute.IDistributeAward;
import org.example.domain.task.service.ITaskService;
import org.example.types.event.BaseEvent;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 奖品发奖消息消费者
 */
@Slf4j
@Component
@RocketMQMessageListener(consumerGroup = "sst-group-send-award", topic = "send_award")
public class SendAwardCustomer implements RocketMQListener<String> {

    private String topic = "send_award";

    @Resource
    private ITaskService taskService;

    @Resource
    private IAwardService awardService;

    @Override
    public void onMessage(String message) {
        try {
            log.info("监听用户奖品发送消息 topic: {} message: {}", topic, message);

            BaseEvent.EventMessage<SendAwardMessageEvent.SendAwardMessage> eventMessage = JSON.parseObject(message, new TypeReference<BaseEvent.EventMessage<SendAwardMessageEvent.SendAwardMessage>>() {
            }.getType());

            SendAwardMessageEvent.SendAwardMessage data = eventMessage.getData();

            DistributeAwardEntity distributeAwardEntity = DistributeAwardEntity.builder()
                    .userId(data.getUserId())
                    .orderId(data.getOrderId())
                    .awardId(data.getAwardId())
                    .awardTitle(data.getAwardTitle())
                    .config(data.getConfig())
                    .build();
            //发放奖品
            awardService.distributeAward(distributeAwardEntity);


        } catch (Exception e) {
            log.error("监听用户奖品发送消息，消费失败 topic: {} message: {}", topic, message);
            throw e;
        }
    }
}
